package com.cloud.controller;

import com.cloud.domain.TOrder;
import com.cloud.service.ITOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器 GUN
 * </p>
 *
 * @author jobob
 * @since 2021-06-24
 */
@RestController
@RequestMapping("/domain/t-order")
public class TOrderController {
    @Autowired
    private ITOrderService iTOrderService;

    @RequestMapping("/getById")
    public TOrder getById(@RequestParam("id") Long id) {
        if (null == id) {
            return null;
        }
        if (id < 0) {
            throw new RuntimeException("错误！");
        }
        return iTOrderService.getById(id);
    }

    @RequestMapping("/save")
    public boolean save(@RequestBody TOrder tOrder) {
        if (null == tOrder) {
            throw new RuntimeException("数据为空，插入失败");
        }
        return iTOrderService.save(tOrder);
    }

    @RequestMapping("/delete")
    public boolean delete(@RequestParam("id") Long id) {
        if (null == id) {
          throw new RuntimeException("数据为空，删除失败");
        }
        return iTOrderService.removeById(id);
    }

    @RequestMapping("/update")
    public boolean update(@RequestBody TOrder tOrder) {
        if (null == tOrder) {
           throw new RuntimeException("数据为空，修改失败");
        }
        return iTOrderService.updateById(tOrder);
    }

    @RequestMapping("/listByPage")
    public PageInfo<TOrder> listByPage(@RequestBody TOrder tOrder) {
        int pageNum = 1;
        int pageSize = 10;
        if (null != tOrder && tOrder.getPageNum() != null) {
            pageNum = tOrder.getPageNum();
        }
        if (null != tOrder && tOrder.getPageSize() != null) {
           pageSize = tOrder.getPageSize();
        }
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<TOrder>(iTOrderService.list());
    }

    @RequestMapping("/listAll")
    public List<TOrder> listAll() {
        return iTOrderService.list();
    }

    private void wait(int second) {
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        }
    }

    @RequestMapping("/timeout")
    public TOrder timeout(@RequestParam("id") Long id) {
        if (null == id) {
            return null;
        }
        wait(3);
        return iTOrderService.getById(id);
    }

}
